package springmvc_demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 不同的响应类型, demo
 */
@Controller
public class ResponseDemoController {

    //********************************* 返回视图 *******************************
    // 结合InternalResourceViewResolver配置使用

    /**
     *  返回视图, 默认将返回结果当做视图名称
     */
    @GetMapping("/response/default")
    public String responseDefault() {
        return "demo/test";
    }

    @GetMapping("/response/modelAndView")
    public ModelAndView modelAndView() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("demo/test");
        return modelAndView;
    }

    @GetMapping("/response/modelAndView1")
    public ModelAndView modelAndView1() {
        return new ModelAndView("demo/test");
    }
    //********************************* 返回视图 *******************************

    /**
     * 返回文本
     * 通过@ResponseBody来描述字符串非视图名称
     */
    @GetMapping("/response/textOrJson")
    @ResponseBody
    public String textOrJson() {
        return "response textOrJson";
    }

    /**
     * 转发
     */
    @GetMapping("/response/forward")
    public String forward(HttpServletRequest request) {
        request.setAttribute("forwardParam", "abc...");
        return "forward:/response/forwardEnd";
    }

    /**
     * 转发被转发url
     */
    @GetMapping("/response/forwardEnd")
    @ResponseBody
    public String forwardEnd(HttpServletRequest request) {
        return "forwardEnd-> forwardParam:"+ request.getAttribute("forwardParam");
    }

    /**
     * 重定向 (对于浏览器属于两次请求,需要在后端处理好参数的传递)
     */
    @GetMapping("/response/redirect")
    public String redirect() {
        return "redirect:/response/default";
    }



}
